const {
  getOrderList,
  getOrderCount,
  editOrderStatus
} = require('../service/order.service');
const { judgeIfMissParam } = require('../utils/common');

class OrderController {
  async getOrderList(ctx, next) {
    try {
      const requireArr = ['page', 'size', 'orderNumber', 'startTime', 'endTime', 'evaluation', 'status'];
      const flag = judgeIfMissParam(ctx, '[order.controller_getOrderList]', requireArr, ctx.query);
      if (!flag) return;
      
      let page = ctx.query.page, size = ctx.query.size;
      // 设置默认的page和size
      let options = {
        ...ctx.query,
        page: ((page -1) * size).toString() || '0',
        size: size.toString() || '10'
      };
      const result = await getOrderList(options);
      const total = await getOrderCount(options);

      // 将时间变为时间戳
      for (let i = 0; i < result.length; i++) {
        if (result[i].createTime) result[i].createTime = result[i].createTime.getTime();
        if (result[i].serverTime) result[i].serverTime = result[i].serverTime.getTime();
        if (result[i].finishTime) result[i].finishTime = result[i].finishTime.getTime();
      }
  
      ctx.body = {
        ret: 0,
        data: {
          list: result,
          page,
          size,
          total
        }
      }
    } catch (e) {
      console.log('[order.controller_getOrderList]', e);
    }
  }

  // 修改订单状态status
  async editOrderStatus(ctx, next) {
    try {
      const requireArr = ['id', 'status'];
      const flag = judgeIfMissParam(ctx, '[order.controller_editOrderStatus]', requireArr, ctx.request.body);
      if (!flag) return;
  
      const result = await editOrderStatus(ctx.request.body);
      if (!result) return;
      ctx.body = {
        ret: 0,
        data: 'ok'
      }
    } catch (e) {
      console.log('[order.controller_editOrderStatus]', e);
    }
  }
}

module.exports = new OrderController();